package service;

import dao.UserDao;
import domain.User;
import exception.ActiveUserException;
import exception.LoginException;
import utils.MailUtils;
import utils.ResponseCode;
import java.sql.Date;
import java.sql.SQLException;

public class UserService {
    private UserDao userDao=new UserDao();
    //面向业务
    public void active(String activeCode) throws  ActiveUserException{
        try {
            User user=userDao.findUserByActiveCode(activeCode);
            if (user==null){
                throw new ActiveUserException(ResponseCode.ERROR_ACTIVE);
            }
            Date registTime= (Date) user.getRegistTime();
            long currentTime=System.currentTimeMillis();
            long time=currentTime-registTime.getTime();
            if (time/1000/60/60>24){
                throw new ActiveUserException(ResponseCode.ERROR_EXPIRE);
            }
            userDao.activeUser(activeCode);
        }catch (SQLException e){

            throw new ActiveUserException(ResponseCode.ERROR_DB);
        }

    }
    public boolean register(User user)  {

        try {

            userDao.addUser(user);
            String emailMsg = "感谢您注册网上书城，点击"
                    + "<a href='http://localhost:8080/api/activeUser?activeCode='"
                    + user.getActiveCode() + "'<a>&nbsp;激活&nbsp;</a>后使用。"
                    + "<br />为保障您的账户安全，请在24小时内完成激活操作";
            MailUtils.sendMail(user.getEmail(), emailMsg);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    public  User login(User user)throws LoginException{

        User useDB= null;
        try {
            useDB= userDao.findUserByUsernameAndPassword(user.getUsername(),user.getPassword());
        }catch (Exception e){
            e.printStackTrace();
            throw  new LoginException(ResponseCode.ERROR_DB);
        }
        if(useDB!=null){
            if(useDB.getState()==1){
                System.out.println("用户为超级用户！");
                return  useDB;
            }
            else {
                throw  new LoginException(ResponseCode.NOT_ACTIVE);
            }
        }
        else {
            throw  new LoginException(ResponseCode.ERROR_NAME_PASSWORD);
        }
    }
}
